<template>
  <div class="price-management">
    <div class="page-header">
      <h2>渠道价格管理</h2>
      <div class="header-actions">
        <el-button @click="goBack">返回渠道列表</el-button>
        <el-button type="primary" @click="openBatchPriceDialog">批量设置价格</el-button>
      </div>
    </div>
    
    <el-card class="channel-info">
      <div class="channel-info-title">渠道信息</div>
      <div class="channel-info-content" v-if="channel">
        <div class="info-item">
          <span class="label">渠道名称：</span>
          <span class="value">{{ channel.name }}</span>
        </div>
        <div class="info-item">
          <span class="label">渠道代码：</span>
          <span class="value">{{ channel.code }}</span>
        </div>
        <div class="info-item">
          <span class="label">状态：</span>
          <el-tag :type="channel.status ? 'success' : 'danger'">
            {{ channel.status ? '启用' : '禁用' }}
          </el-tag>
        </div>
      </div>
    </el-card>
    
    <el-card class="price-filter">
      <div class="filter-form">
        <el-form :inline="true" :model="filterForm">
          <el-form-item label="分类">
            <el-select v-model="filterForm.categoryId" placeholder="选择分类" clearable>
              <el-option
                v-for="category in categories"
                :key="category.id"
                :label="category.name"
                :value="category.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="关键词">
            <el-input
              v-model="filterForm.keyword"
              placeholder="商品名称关键词"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    
    <el-card>
      <el-table
        v-loading="loading"
        :data="prices.items"
        style="width: 100%"
        border
      >
        <el-table-column type="index" width="50" />
        <el-table-column label="商品图片" width="80">
          <template #default="{ row }">
            <el-image
              v-if="row.product.imageUrl"
              :src="row.product.imageUrl"
              style="width: 40px; height: 40px;"
              fit="contain"
            />
            <span v-else>无</span>
          </template>
        </el-table-column>
        <el-table-column label="商品名称" prop="product.name" width="150" />
        <el-table-column label="分类" prop="product.category.name" width="100" />
        <el-table-column label="标准价格" width="100">
          <template #default="{ row }">
            ¥{{ row.product.price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="渠道价格" width="100">
          <template #default="{ row }">
            ¥{{ row.price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="折扣" width="80">
          <template #default="{ row }">
            <span v-if="row.discount">{{ (row.discount * 100).toFixed(0) }}%</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="差价" width="80">
          <template #default="{ row }">
            <span :class="getPriceDiffClass(row.price - row.product.price)">
              {{ (row.price - row.product.price).toFixed(2) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="80" fixed="right">
          <template #default="{ row }">
            <el-button
              size="small"
              type="primary"
              @click="openEditPriceDialog(row)"
            >
              修改
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:currentPage="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="prices.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 修改价格对话框 -->
    <el-dialog
      v-model="priceDialogVisible"
      title="修改商品价格"
      width="500px"
    >
      <div class="product-info" v-if="currentProduct">
        <div class="product-image">
          <el-image
            v-if="currentProduct.product.imageUrl"
            :src="currentProduct.product.imageUrl"
            fit="contain"
            style="width: 80px; height: 80px;"
          />
        </div>
        <div class="product-details">
          <div class="product-name">{{ currentProduct.product.name }}</div>
          <div class="product-category">分类：{{ currentProduct.product.category.name }}</div>
          <div class="product-price">标准价格：¥{{ currentProduct.product.price.toFixed(2) }}</div>
        </div>
      </div>
      
      <el-form
        ref="priceFormRef"
        :model="priceForm"
        :rules="priceRules"
        label-width="100px"
        class="price-form"
      >
        <el-form-item label="渠道价格" prop="price">
          <el-input-number
            v-model="priceForm.price"
            :precision="2"
            :step="0.1"
            :min="0"
            controls-position="right"
          />
        </el-form-item>
        
        <el-form-item label="折扣" prop="discount">
          <el-slider
            v-model="priceForm.discountPercent"
            :min="0"
            :max="200"
            :step="1"
            :format-tooltip="formatDiscount"
            @input="handleDiscountChange"
          />
          <div class="discount-text">{{ formatDiscount(priceForm.discountPercent) }}</div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="priceDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPriceForm" :loading="submitting">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 批量设置价格对话框 -->
    <el-dialog
      v-model="batchPriceDialogVisible"
      title="批量设置价格"
      width="600px"
    >
      <el-form
        ref="batchPriceFormRef"
        :model="batchPriceForm"
        label-width="120px"
      >
        <el-form-item label="批量设置方式">
          <el-radio-group v-model="batchPriceForm.mode">
            <el-radio :label="'discount'">按折扣设置</el-radio>
            <el-radio :label="'fixed'">固定价格</el-radio>
            <el-radio :label="'increase'">增加金额</el-radio>
            <el-radio :label="'decrease'">减少金额</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="商品分类">
          <el-select v-model="batchPriceForm.categoryId" placeholder="选择分类" clearable>
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item
          :label="
            batchPriceForm.mode === 'discount'
              ? '折扣率(%)'
              : batchPriceForm.mode === 'fixed'
              ? '固定价格'
              : batchPriceForm.mode === 'increase'
              ? '增加金额'
              : '减少金额'
          "
        >
          <el-input-number
            v-model="batchPriceForm.value"
            :precision="batchPriceForm.mode === 'discount' ? 0 : 2"
            :step="batchPriceForm.mode === 'discount' ? 1 : 0.1"
            :min="batchPriceForm.mode === 'discount' ? 0 : 0"
            :max="batchPriceForm.mode === 'discount' ? 200 : undefined"
            controls-position="right"
          />
          <div class="form-tip" v-if="batchPriceForm.mode === 'discount'">
            输入90表示9折，100表示不打折，110表示1.1倍
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="batchPriceDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitBatchPriceForm" :loading="submitting">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import api from '@/utils/api'

const route = useRoute()
const router = useRouter()
const channelId = route.params.id

// 加载状态
const loading = ref(false)
const submitting = ref(false)

// 渠道信息
const channel = ref(null)

// 商品分类
const categories = ref([])

// 商品价格列表
const prices = reactive({
  items: [],
  total: 0,
  page: 1,
  pageSize: 20,
  totalPages: 0
})

// 筛选表单
const filterForm = reactive({
  categoryId: '',
  keyword: ''
})

// 分页信息
const pagination = reactive({
  page: 1,
  pageSize: 20
})

// 价格对话框
const priceDialogVisible = ref(false)
const priceFormRef = ref(null)
const currentProduct = ref(null)

// 价格表单
const priceForm = reactive({
  price: 0,
  discount: null,
  discountPercent: 100 // 用于显示的百分比值
})

// 价格表单验证规则
const priceRules = {
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '价格不能小于0', trigger: 'blur' }
  ]
}

// 批量设置价格对话框
const batchPriceDialogVisible = ref(false)
const batchPriceFormRef = ref(null)

// 批量设置价格表单
const batchPriceForm = reactive({
  mode: 'discount', // discount, fixed, increase, decrease
  categoryId: '',
  value: 100 // 默认不打折
})

// 获取渠道信息
const fetchChannelInfo = async () => {
  try {
    const response = await api.get(`/channels/${channelId}`)
    if (response.data && response.data.status === 'success') {
      channel.value = response.data.data
    } else {
      ElMessage.warning('获取渠道信息失败')
    }
  } catch (error) {
    console.error('获取渠道信息失败:', error)
    ElMessage.error('获取渠道信息失败: ' + (error.response?.data?.message || error.message))
  }
}

// 获取商品分类
const fetchCategories = async () => {
  try {
    const response = await api.get('/categories')
    if (response.data && response.data.status === 'success') {
      categories.value = response.data.data
    } else {
      ElMessage.warning('获取商品分类失败')
    }
  } catch (error) {
    console.error('获取商品分类失败:', error)
    ElMessage.error('获取商品分类失败: ' + (error.response?.data?.message || error.message))
  }
}

// 获取渠道商品价格
const fetchChannelPrices = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.page,
      pageSize: pagination.pageSize,
      categoryId: filterForm.categoryId || undefined,
      keyword: filterForm.keyword || undefined,
      showAllProducts: true // 添加参数，表示显示所有商品，包括未设置价格的商品
    };
    
    const response = await api.get(`/channels/${channelId}/prices`, { params });
    if (response.data && response.data.status === 'success') {
      prices.items = response.data.data.items;
      prices.total = response.data.data.total;
      prices.page = response.data.data.page;
      prices.pageSize = response.data.data.pageSize;
      prices.totalPages = response.data.data.totalPages;
    } else {
      ElMessage.warning('获取渠道商品价格失败');
    }
  } catch (error) {
    console.error('获取渠道商品价格失败:', error);
    ElMessage.error('获取渠道商品价格失败: ' + (error.response?.data?.message || error.message));
  } finally {
    loading.value = false;
  }
};

// 返回渠道列表
const goBack = () => {
  router.push('/admin/channels')
}

// 处理搜索
const handleSearch = () => {
  pagination.page = 1 // 重置页码
  fetchChannelPrices()
}

// 重置筛选条件
const resetFilter = () => {
  filterForm.categoryId = ''
  filterForm.keyword = ''
  handleSearch()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  pagination.page = page
  fetchChannelPrices()
}

// 处理每页条数变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.page = 1 // 重置页码
  fetchChannelPrices()
}

// 获取价格差异的样式类
const getPriceDiffClass = (diff) => {
  if (diff > 0) return 'price-higher'
  if (diff < 0) return 'price-lower'
  return ''
}

// 打开编辑价格对话框
const openEditPriceDialog = (row) => {
  currentProduct.value = row
  
  // 设置表单初始值
  priceForm.price = row.price
  
  // 计算折扣百分比
  if (row.discount) {
    priceForm.discount = row.discount
    priceForm.discountPercent = Math.round(row.discount * 100)
  } else {
    // 计算实际折扣率
    const calculatedDiscount = row.product.price > 0 ? row.price / row.product.price : 1
    priceForm.discount = calculatedDiscount
    priceForm.discountPercent = Math.round(calculatedDiscount * 100)
  }
  
  priceDialogVisible.value = true
  
  // 在下一个 tick 后重置表单校验结果
  setTimeout(() => {
    priceFormRef.value?.clearValidate()
  }, 0)
}

// 处理折扣变化
const handleDiscountChange = (percent) => {
  if (!currentProduct.value) return
  
  // 更新折扣
  priceForm.discount = percent / 100
  
  // 根据折扣计算价格
  priceForm.price = Number((currentProduct.value.product.price * priceForm.discount).toFixed(2))
}

// 格式化折扣显示
const formatDiscount = (percent) => {
  return `${percent}% (${percent / 100}倍)`
}

// 提交价格表单
const submitPriceForm = async () => {
  // 表单验证
  await priceFormRef.value.validate()
  
  submitting.value = true
  try {
    const response = await api.post(`/channels/${channelId}/prices`, {
      productId: currentProduct.value.product.id,
      price: priceForm.price,
      discount: priceForm.discount
    })
    
    if (response.data && response.data.status === 'success') {
      ElMessage.success(response.data.message || '商品价格设置成功')
      priceDialogVisible.value = false
      fetchChannelPrices() // 刷新列表
    } else {
      ElMessage.warning(response.data?.message || '操作失败')
    }
  } catch (error) {
    console.error('设置商品价格失败:', error)
    ElMessage.error('操作失败: ' + (error.response?.data?.message || error.message))
  } finally {
    submitting.value = false
  }
}

// 打开批量设置价格对话框
const openBatchPriceDialog = () => {
  batchPriceForm.mode = 'discount'
  batchPriceForm.categoryId = ''
  batchPriceForm.value = 100 // 默认不打折
  
  batchPriceDialogVisible.value = true
}

// 提交批量设置价格表单
const submitBatchPriceForm = async () => {
  if (batchPriceForm.value === undefined || batchPriceForm.value === null) {
    ElMessage.warning('请输入有效的数值')
    return
  }
  
  // 确认操作
  try {
    await ElMessageBox.confirm(
      '确定要批量设置商品价格吗？此操作可能会影响大量商品。',
      '批量操作确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
  } catch (e) {
    return // 用户取消操作
  }
  
  submitting.value = true
  try {
    // 构建查询参数
    const params = {
      categoryId: batchPriceForm.categoryId || undefined,
      keyword: undefined
    }
    
    // 先获取符合条件的所有商品
    const response = await api.get(`/channels/${channelId}/prices`, {
      params: {
        ...params,
        page: 1,
        pageSize: 1000 // 一次获取足够多的商品
      }
    })
    
    if (response.data && response.data.status === 'success') {
      const items = response.data.data.items
      
      if (items.length === 0) {
        ElMessage.warning('没有找到符合条件的商品')
        submitting.value = false
        return
      }
      
      // 构建批量更新数据
      const prices = items.map(item => {
        let price = item.price
        
        // 根据不同模式计算价格
        switch (batchPriceForm.mode) {
          case 'discount':
            // 按折扣率计算
            price = Number((item.product.price * (batchPriceForm.value / 100)).toFixed(2))
            break
          case 'fixed':
            // 固定价格
            price = Number(batchPriceForm.value)
            break
          case 'increase':
            // 增加金额
            price = Number((item.price + Number(batchPriceForm.value)).toFixed(2))
            break
          case 'decrease':
            // 减少金额
            price = Number(Math.max(0, (item.price - Number(batchPriceForm.value))).toFixed(2))
            break
        }
        
        return {
          productId: item.product.id,
          price,
          discount: batchPriceForm.mode === 'discount' ? batchPriceForm.value / 100 : null
        }
      })
      
      // 发送批量更新请求
      const updateResponse = await api.post(`/channels/${channelId}/batch-prices`, {
        prices
      })
      
      if (updateResponse.data && updateResponse.data.status === 'success') {
        ElMessage.success(updateResponse.data.message || '批量设置价格成功')
        batchPriceDialogVisible.value = false
        fetchChannelPrices() // 刷新列表
      } else {
        ElMessage.warning(updateResponse.data?.message || '操作失败')
      }
    } else {
      ElMessage.warning('获取商品数据失败')
    }
  } catch (error) {
    console.error('批量设置价格失败:', error)
    ElMessage.error('操作失败: ' + (error.response?.data?.message || error.message))
  } finally {
    submitting.value = false
  }
}

// 初始化
onMounted(() => {
  fetchChannelInfo()
  fetchCategories()
  fetchChannelPrices()
})

// 监听筛选条件变化
watch([() => pagination.page, () => pagination.pageSize], () => {
  fetchChannelPrices()
})
</script>

<style scoped>
.price-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.channel-info, .price-filter {
  margin-bottom: 20px;
}

.channel-info-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #303133;
}

.channel-info-content {
  display: flex;
  flex-wrap: wrap;
}

.info-item {
  margin-right: 30px;
  margin-bottom: 10px;
}

.info-item .label {
  color: #909399;
  margin-right: 5px;
}

.info-item .value {
  color: #303133;
  font-weight: 500;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.price-higher {
  color: #f56c6c;
}

.price-lower {
  color: #67c23a;
}

.product-info {
  display: flex;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.product-image {
  margin-right: 15px;
}

.product-details {
  flex: 1;
}

.product-name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 5px;
}

.product-category, .product-price {
  color: #606266;
  margin-bottom: 5px;
}

.price-form {
  margin-top: 20px;
}

.discount-text {
  text-align: center;
  margin-top: 5px;
  color: #606266;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}
</style> 